package com.swift.client.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

/**
 * @author zl
 * @version 1.0
 * @date 2021/9/28 9:17
 */
@Component
@Slf4j
public class UdpClient1 {

    public  final int MessageReceived = 0x99;
    private  int scanPort = 2557;


    private class CLientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            String body = packet.content().toString(CharsetUtil.UTF_8);
            System.out.println(body);
            Thread.sleep(10000);
            //向客户端发送消息
            String json = "来自client1: 南无阿弥陀佛";
            // 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
            byte[] bytes = json.getBytes("UTF-8");
            DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), packet.sender());
            ctx.writeAndFlush(data);//向客户端发送消息
        }
    }

    @PostConstruct
    private void startClient1() {
        new Thread(()->{
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioDatagramChannel.class)
                        .option(ChannelOption.SO_BROADCAST,true)
                        .option(ChannelOption.SO_RCVBUF, 2048 * 1024)// 设置UDP读缓冲区为2M
                        .option(ChannelOption.SO_SNDBUF, 1024 * 1024)// 设置UDP写缓冲区为1M
                        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // 线程池复用缓冲区
                        .handler(new CLientHandler());

                Channel ch = b.bind(2558).sync().channel();

                ch.writeAndFlush(new DatagramPacket(
                        Unpooled.copiedBuffer("来自client1客户端:南无本师释迦牟尼佛", CharsetUtil.UTF_8),
                        new InetSocketAddress("127.0.0.1", scanPort))).sync();
                log.info("发送client1");
                ch.closeFuture().await();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }).start();
    }

}
